package view;

import com.alibaba.fastjson.JSON;
import com.sun.jersey.core.impl.provider.entity.XMLRootObjectProvider;
import mode.ViewForGrid;
import pond.common.S;
import pond.db.Record;
import pond.db.sql.Sql;
import pond.web.Render;
import pond.web.Router;
import sun.java2d.pipe.AlphaPaintPipe;
import tools.CreateViewTool;

import java.util.List;

/**
 * Created by sky_wang on 2017/2/22.
 */
public class CreateView  extends Router {
    {

        get("/all_data_tables", (req, resp) -> {
            CreateViewTool cvt = new CreateViewTool(App.DB);
            resp.render(Render.json(cvt.getJsonOfDataTable()));
        });

        get("/all_values_of_coloumn", (req, resp) -> {
            String coloumn_name = req.param("coloumn");
            String table_name = req.param("table");
            String sql = "select distinct " + coloumn_name + " from " + table_name + ";";
            List<Record> ret = App.DB.get(t -> t.query(sql));
            resp.render(Render.json(ret));
        });

        post("/new_view", (req, resp) -> {
            CreateViewTool cvt = new CreateViewTool(App.DB);
            String json = req.param("data");
            String options = req.param("options");

            List<ViewForGrid> ret = App.DB.get(t -> t.query(ViewForGrid.class, "select * from view_for_grid where view_name = '" + cvt.getValueByKeyFromJson("view_name", json) + "';"));
            if (ret.size() >= 1) {
                resp.send(403, "view exists");
                return;
            }

            String sql = cvt.getCreateViewSql(json);
            App.DB.post(t -> t.exec(sql));
            ViewForGrid vfg = new ViewForGrid();
            vfg.setId(S.uuid.vid());
            vfg.set("view_name", cvt.getValueByKeyFromJson("view_name", json));
            vfg.set("main_table", cvt.getValueByKeyFromJson("main_table", json));
            vfg.set("query_options_html", cvt.getValueByKeyFromJson("query_options_html", json));
            vfg.set("query_options_ids", cvt.getValueByKeyFromJson("query_options_ids", json));
            vfg.set("grid_options", options);
            vfg.set("view_sql", sql);
            App.DB.post(t -> {
                t.recordInsert(vfg);
            });
            resp.send(200, "ok");
        });

    }
}
